package com.chuangke.common.express.parse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

public class AggregatParser {

	public static final List<String> AGG_FUNCTION_LIST;

	static {
		AGG_FUNCTION_LIST = new ArrayList<>();
		AGG_FUNCTION_LIST.add("sum");
		AGG_FUNCTION_LIST.add("avg");
	}

	public static Parser parse(String formula) {
		formula = formula.replaceAll(" ", "").trim();
		Parser parser = new Parser();
		parser.setSrcFormula(formula);

		Map<String, String> subFormulaMap = new HashMap<>();

		StringTokenizer strToken = new StringTokenizer(formula, "+-*/()", true);
		boolean flag = false;
		int count = 0;
		int fcount = 1;
		StringBuilder subFormula = new StringBuilder();
		while (strToken.hasMoreTokens()) {
			String token = strToken.nextToken();
			if (AGG_FUNCTION_LIST.contains(token.toLowerCase())) {
				flag = true;
				continue;
			}

			if (flag && "(".equals(token) && count == 0) {
				count++;
				continue;
			}

			if (flag) {
				if ("(".equals(token)) {
					count++;
				}
				if (")".equals(token)) {
					count--;
				}
				if (count > 0) {
					subFormula.append(token);
				} else if (count == 0) {
					flag = false;
					subFormulaMap.put("PP" + fcount, subFormula.toString());
					fcount++;
					subFormula.setLength(0);
				}
			}
		}

		parser.setSubFormulaMap(subFormulaMap);
		for (Map.Entry<String, String> entry : subFormulaMap.entrySet()) {
			formula = formula.replace(entry.getValue(), entry.getKey());
		}
		parser.setNewFormula(formula);
		return parser;
	}

	public static void main(String[] args) {
		String formula = " sum   (a +  b  )+avg(b/(5+c))";
		Parser parser = parse(formula);
		System.out.println(parser);
	}
}
